package tech.mhuang.pacebox.springboot.autoconfiguration.trace.sms;

import com.alibaba.fastjson2.JSON;
import io.opentracing.Span;
import io.opentracing.Tracer;
import io.opentracing.tag.Tags;
import lombok.extern.slf4j.Slf4j;
import tech.mhuang.pacebox.core.chain.BaseChain;
import tech.mhuang.pacebox.core.exception.ExceptionUtil;
import tech.mhuang.pacebox.core.util.ObjectUtil;
import tech.mhuang.pacebox.sms.domain.SmsSendRequest;
import tech.mhuang.pacebox.sms.domain.SmsSendResult;
import tech.mhuang.pacebox.sms.inteceptor.SmsSendInterceptor;

import java.util.Map;

/**
 * 短信埋点
 *
 * @author mhuang
 * @since 1.0.0
 */
@Slf4j
public class TraceSmsTemplateInteceptor implements SmsSendInterceptor {

    private final Tracer tracer;


    public TraceSmsTemplateInteceptor(Tracer tracer) {
        this.tracer = tracer;
    }

    @Override
    public SmsSendResult interceptor(BaseChain<SmsSendRequest, SmsSendResult> chain) {
        SmsSendResult result;
        SmsSendRequest request = chain.request();
        Span span = tracer.buildSpan(request.getType())
                .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT)
                .start();
        Tags.COMPONENT.set(span, "sms");
        span.setTag("request.body", JSON.toJSONString(request));
        try {
            result = chain.proceed(request);
            if (ObjectUtil.isEmpty(result.getThrowable())) {
                span.setTag("response.body", JSON.toJSONString(result));
            } else {
                Tags.ERROR.set(span, true);
                Throwable e = result.getThrowable();
                Map<String, String> log = ExceptionUtil.logsForException(e);
                log.put("event", Tags.ERROR.getKey());
                span.log(log);
            }
        } finally {
            span.finish();
        }
        return result;
    }
}
